package team.hyznrj.studentsys.converter;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import team.hyznrj.studentsys.dao.repository.AcademicYearsRepository;
import team.hyznrj.studentsys.dto.ConductScoreDto;
import team.hyznrj.studentsys.entity.AcademicYears;
import team.hyznrj.studentsys.entity.ConductScore;

import java.util.List;
import java.util.stream.Collectors;

import static org.codehaus.groovy.runtime.DefaultGroovyMethods.collect;

/**
 * @author ReMidDream
 * @date 2018-04-09 20:52
 **/
@Component
public class ConductScoreDto2ConductScore {

    @Autowired
    private AcademicYearsRepository academicYearsRepository;

    public List<ConductScore> converter(List<ConductScoreDto> conductScoreDtos){
        List<AcademicYears> academicYearsList = academicYearsRepository.findAll();

        return conductScoreDtos.stream().map(conductScoreDto ->{
        ConductScore conductScore = new ConductScore();
        Integer academicYearId = null;

        //判断是否存在于学年表
        for (AcademicYears academicYear : academicYearsList) {
            if (academicYear.getAcademicYear().equals(conductScoreDto.getAcademicYear())) {
                academicYearId = academicYear.getId();
                break;
            }
        }
        //若学年表不存在则添加至学年表
        if (academicYearId==null) {
            AcademicYears academicYears = new AcademicYears(conductScoreDto.getAcademicYear());
            academicYearId = academicYearsRepository.save(academicYears).getId();
        }
        BeanUtils.copyProperties(conductScoreDto,conductScore);
        conductScore.setAcademicYear(academicYearId);
        return conductScore;
        }).collect(Collectors.toList());
    }
}
